package com.gionee.navil.lockscreen;

import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class GnCheckLongPressHelper {
	private View mView;
	private boolean mHasPerformedLongPress;
	private CheckForLongPress mPendingCheckForLongPress;
	private float mDownX, mDownY;
	private int mLongPressTimeout;
	private int mScaledTouchSlop;

	class CheckForLongPress implements Runnable {
		public void run() {
			if ((mView.getParent() != null) && mView.hasWindowFocus()
					&& !mHasPerformedLongPress) {
				if (mView.performLongClick()) {
					mView.setPressed(false);
					mHasPerformedLongPress = true;
				}
			}
		}
	}

	public GnCheckLongPressHelper(View v) {
		mScaledTouchSlop = ViewConfiguration.get(v.getContext())
				.getScaledTouchSlop();
		mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
		mView = v;
	}

	public void postCheckForLongPress(MotionEvent ev) {
		mDownX = ev.getX();
		mDownY = ev.getY();
		mHasPerformedLongPress = false;

		if (mPendingCheckForLongPress == null) {
			mPendingCheckForLongPress = new CheckForLongPress();
		}
		mView.postDelayed(mPendingCheckForLongPress, mLongPressTimeout);
	}

	public void onMove(MotionEvent ev) {
		float x = ev.getX();
		float y = ev.getY();
		boolean xMoved = Math.abs(mDownX - x) > mScaledTouchSlop;
		boolean yMoved = Math.abs(mDownY - y) > mScaledTouchSlop;

		if (xMoved || yMoved) {
			cancelLongPress();
		}
	}

	public void cancelLongPress() {
		mHasPerformedLongPress = false;
		if (mPendingCheckForLongPress != null) {
			mView.removeCallbacks(mPendingCheckForLongPress);
			mPendingCheckForLongPress = null;
		}
	}

	public boolean hasPerformedLongPress() {
		return mHasPerformedLongPress;
	}
}
